<template>
  <view class="order">
    <u-tabs 
    :list="tabsList" 
    :current="currentTabIndex" 
     itemStyle="font-size:14px;lineHeight:88rpx;background:#fff" 
     lineWidth="40" 
     @change="onTabChange" 
     lineColor="#ee0a24"
     :activeStyle="{
        color: '#303133',
        fontWeight: 'bold',
        transform: 'scale(1.05)'
      }"
      :inactiveStyle="{
        color: '#606266',
        transform: 'scale(1)'
      }"
     >
     </u-tabs>
    <order-list :orders="orders" :query="query" :isLast="isLast" :isFistEnter="isFistEnter" @call="callbackAction"></order-list>
  </view>

</template>


<script lang='ts'>
  import {
    Component,
    Mixins
  } from 'vue-property-decorator'
  import {
    getOrders
  } from "@/api";
  import OrderMix from "@/mixins/order";
  import isNumber from "lodash/isNumber";
  import {
    getAfterSaleList
  } from "@/api/modules/afterSale";
  import OrderItem from "./order-item/order-item.vue"
  import DataEmpty from '@/components/data-empty/data-empty.vue';
  import OrderList from './order-list/order-list.vue';

  const order = require("./order.wxs");
  const af = require("@/wxs/afterSale.wxs");
  

  @Component({
    components: {
      OrderItem,
      DataEmpty,
      OrderList
    }
  })
  export default class Order extends Mixins(OrderMix) {

    order = order;
    af = af;

    /** 当前tab携参 */
    active: string = "-1"
    // 当前tab的下标
    currentTabIndex=0
    /** 订单列表 */
    orders: any = []
    /** 订单查询条件 */
    query: any = {
      current: 1,
      keyword: "",
      /**
       * -1：所有订单, 0.待付款（待买家付款）,
       *  1.待发货（买家已付款）,
       *  3.待提货（物流订单已发货）, 4.已完成（用户已经签收）,
       *  5.待评价, 6.售后订单, 7.已关闭
       */
      orderStatus: "-1",
      size: 10,
    }
    /** 是否为最后一条记录 */
    isLast: boolean = false
    /** 是否为第一次进度 */
    isFistEnter: boolean = true
    // tab选项
    tabsList=[{
      name:"全部",
      type:"-1"
    },{
      name:"待付款",
      type:"0"
    },{
      name:"待发货",
      type:"1"
    },{
      name:"待提货",
      type:"3"
    },{
      name:"已完成",
      type:"4"
    },{
      name:"待评价",
      type:"5"
    },{
      name:"售后订单",
      type:"6"
    },{
      name:"已关闭",
      type:"7"
    }]
    tabClickHandle(n){
      console.log(n)
    }
    get hasOpenEvaluate(){
      return this.$store.state.settingStore.shopSetting.hasOpenEvaluate
    }

    // get show() {
    //   return this.$store.state.settingStore.isReady
    // }

    // 页面周期函数--监听页面加载
    onLoad(options) {
      // this.active = "-1"
      const type = options.type || "-1"
      const normalTabIndex = options.type?this.tabsList.map((item,index)=>{
        return item.type===options.type?index:0
      }).filter(Boolean)[0]:0
      if (this.$store.state.settingStore.isReady) {
        this.setData({
          active: type,
          ["query.orderStatus"]:normalTabIndex?type:'-1',
          currentTabIndex:normalTabIndex
        }, () => {
          this.getOrderslist();
        });
      }

      this.$Pubsub.on("app-launch", () => {
        this.setData({
          active: type,
          currentTabIndex:normalTabIndex
        }, () => {
          this.getOrderslist();
        });
      });
    }
    // 页面周期函数--监听页面显示(not-nvue)
    async onShow() {
      await this.$store.dispatch('settingStore/getSetting')
      if (this.isFistEnter) {
        this.setData({
          isFistEnter: false
        });
        return
      } else {
        this.getOrderslist({
          current: 1
        }, true);
      }
    }
    // 页面处理函数--监听用户上拉触底
    onReachBottom() {
      this.setData({
        "query.current": ++this.query.current
      });
      this.getOrderslist();
    }

    /** mixins内成功回调 */
    callbackAction() {
      this.getOrderslist({
        current: 1
      }, true);
    }

    /** tab changge事件 */
  async onTabChange({
      // detail: {
      //   name: orderStatus
      // }
      type,
      index
    }) {
      this.orders = []
      this.updateQuery({
        orderStatus:type,
        current: 1
      });
      this.getOrderslist({}, false, () => {
        this.setData({
          active: type,
          currentTabIndex:index
        });
      });
    }

    /** 更新查询条件 */
    updateQuery(params) {
      this.setData({
        query: {
          ...this.query,
          ...params
        },
        isLast: false,
      });
    }

    /** 处理倒计时结束 */
    onFinish() {
      this.getOrderslist({}, true);
    }

    /**
     * 获取订单列表
     * @param query
     * @param refresh
     */
    async getOrderslist(query: any = {}, refresh = false, cb ? ) {
      /** 如果已为最后一条记录，跳过请求 */
      if (this.isLast && !refresh) {
        cb && cb();
        return;
      }
      uni.showLoading({
        title:"加载中..."
      })
      const res = this.query.orderStatus === "6" ? await getAfterSaleList({
        ...this.query,
        ...query
      }) : await getOrders({
        ...this.query,
        ...query
      })
      const {
        current,
        pages,
        list
      } = res;
      this.setData({
        orders: this.handOrderList(
          current > 1 && !refresh ? [...this.orders, ...list] : list,
        ),
      });
      
      // const tabs = this.$refs.tabs as any
      // tabs.resize()
      /** 如果为最后一页设置到底状态 */
      if (current === pages) {
        this.setData({
          isLast: true
        });
      }
      cb && cb();
      uni.hideLoading()
    }

    /** 设置倒计时 */
    handOrderList(list: any[]) {
      return list.map(item => {
        if (item.payAmount && item.payAmount.toFixed) {
          item.payAmount = item.payAmount.toFixed(2);
        }
        if (item.expireTime && !isNumber(item.expireTime)) {
          item.expireTime = +new Date(item.expireTime.replace(/-/gi, "/")) - +new Date();
        }

        let status = false;

        if (item.itemVoList) {
          item.itemVoList.map(goods => {
            if (goods.afs) {
              if (!status) {
                status = this.receiptDisabled(goods.afs);
              }
            }
          });
        }

        item.disabled = status;
        return item;
      });
    }
  }
</script>

<style lang="scss" scoped>
  @import "@/assets/styles/_var.scss";

  page {
    background: $main-background;
  }

  .order {
    &__button {
      @include flex(flex-end);
    }

    &__top {
      @include flex();

      &--copy {
        margin-left: 10px;
      }
    }

    &__expire {
      @include flex();

      .van-count-down {
        // background-color: red;
        position: relative;
        bottom: -1rpx;
        color: $main-light-color;
        margin: 0 3px;
      }
    }

    &__status {
      position: relative;
      top: -14rpx;
    }

    .van-dialog__message {
      padding: 30rpx;
    }

    .van-dialog__message-text {
      font-size: 16px;
    }
  }
</style>